package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetMealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetMealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService{

    @Autowired
    private SetMealDao setMealDao;

    //使用JedisPool操作redis服务
    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;//从属性文件中读取要生成的html对应的目录

    //新增套餐信息,同时需要关联检查组
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //新增套餐信息,操作t_setmeal
        setMealDao.add(setmeal);
        //设置套餐和检查组的多对多关系,操作t_setmeal_checkgroup
        //获取新增的id值
        Integer setmealId = setmeal.getId();
        this.setSetMealAndCheckGroup(setmealId,checkgroupIds);

        //将图片名称保存到redis集合中
        String fileName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);

        //当添加套餐后需要重新生成静态页面(套餐列表页面,套餐详情页面)
        generateMobileStaticHtml();
    }

    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml(){

        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setMealDao.findAll();

        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);
        //需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list){
        Map map = new HashMap();
        //为模板提供数据用于生成静态页面
        map.put("setmealList",list);//"setmealList":模板数据名
        generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);//"mobile_setmeal.ftl":模板文件名
    }

    //生成套餐详情静态页面(可能有多个)
    public void generateMobileSetmealDetailHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal",setMealDao.findById(setmeal.getId()));//"setmeal":模板数据名
            generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);//"mobile_setmeal_detail.ftl":模板文件名,"setmeal_detail_":生成的详情页面前缀
        }
    }


    //通用方法,用于生成静态页面
    public void  generateHtml(String templateName,String htmlPageName,Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();//获取配置对象
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outPutPath+"/"+htmlPageName));
            //输出文件
            template.process(map,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();//当前页
        Integer pageSize = queryPageBean.getPageSize();//每页显示条数
        String queryString = queryPageBean.getQueryString();//查询条件

        //完成分页查询,基于Mybatis框架提供的分页助手插件完成
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page = setMealDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<Setmeal> rows = page.getResult();

        return new PageResult(total,rows);
    }

    //查询所有套餐
    @Override
    public List<Setmeal> findAll() {
        return setMealDao.findAll();
    }

    //根据套餐id查询套餐详情(包括套餐基本信息,套餐包含的检查组,检查组包含的检查项)
    @Override
    public Setmeal findById(Integer id) {
        return setMealDao.findById(id);
    }

    //查询套餐预约占比数据
    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setMealDao.findSetmealCount();
    }

    //方法抽取:建立套餐和检查组多对多的关联关系
    public void setSetMealAndCheckGroup(Integer setmealId,Integer[] checkgroupIds){
        if(checkgroupIds != null && checkgroupIds.length > 0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("setmealId",setmealId);
                map.put("checkgroupId",checkgroupId);
                setMealDao.setSetmealAndCheckGroup(map);
            }
        }
    }

}
